import { useEffect, useState, useMemo } from 'react';
import { ExclamationCircleOutlined, CloseCircleOutlined, SelectOutlined, PlusCircleOutlined, EditOutlined } from '@ant-design/icons';
import { InputNumber, Popover, Form, Button, Input, Checkbox, message } from 'antd';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import { setProductInfo } from '@/store/actions/order';
import { validateIDCard } from '@/utils';
// css
import styles from '@/styles/CommonOrder.module.scss';
// api
import { customerList as _getCustomerList, addCustomer as _addCustomer } from '@/api/order';

const { TextArea } = Input;

const setSelectCustomerToCookie = (c_list) => {
    Cookies.set('order_select_customers', JSON.stringify(c_list))
}

// 防抖
let timer = null;

const OrderForm = ({ _setProductInfo, order: { date }, data: { target, goodsId, goodsExtendName, realName, buyLimit } }) => {

    const userInfo = JSON.parse(Cookies.get('userInfo') || "{}");
    const { orderNumberType, orderNumberLess, orderNumberMore } = buyLimit || {};
    const isHotel = useMemo(() => target === '/hotel', [target]);

    const [form] = Form.useForm();

    const [customerList, setCustomerList] = useState([]);
    const [updateId, setUpdateId] = useState("");

    const [maxNum, setMaxNum] = useState(99);
    const [minNum, setMinNum] = useState(1);
    const [orderNum, setOrderNum] = useState(1);
    const [contact, setContact] = useState('');
    const [telephone, setPhone] = useState(userInfo?.phone);
    const [idcard, setIdcard] = useState('');
    const [remark, setRemark] = useState('');

    useEffect(() => {
        realName > 1 && getCustomerList();
        // 购买数量限制
        if (orderNumberType === 2) {
            if (orderNumberLess > 0) {
                setMinNum(orderNumberLess);
                setOrderNum(orderNumberLess);
                Cookies.set('order_number', orderNumberLess);
            }
            if (orderNumberMore > 0) {
                setMaxNum(orderNumberMore);
            }
        }
        Cookies.set('order_phone', userInfo?.phone);
    }, []);

    // 获取游客列表信息
    function getCustomerList() {
        _getCustomerList().then(res => {
            const { code, data } = res;
            if (code === 0 && data) {
                customerList.forEach(c => {
                    data.forEach(d => {
                        if (c.id === d.id && c.checked) {
                            d.checked = true
                        }
                    })
                })
                setCustomerList([...data]);
                setSelectCustomerToCookie(data);
            }
        })
    }
    // 更改数量
    function onNumberChange(value) {
        if (!value && value !== 0) return;
        if (timer) clearTimeout(timer);
        const startDate = isHotel ? Cookies.get('order_hotel_startDate') : (date || Cookies.get('order_select_date')),
            endDate = isHotel ? Cookies.get('order_hotel_endDate') : (date || Cookies.get('order_select_date'));
        timer = setTimeout(() => {
            _setProductInfo({
                goodsId,
                goodsExtendName,
                startDate,
                endDate,
                amount: value,
                specificationsValueIds: Cookies.get('order_spIds')
            })
        }, 500);
        setOrderNum(value);
        Cookies.set('order_number', value)
    }
    // 填写姓名/手机号/备注
    function onChangeContact(value) {
        setContact(value);
        Cookies.set('order_contact', value)
    }
    function onChangePhone(value) {
        setPhone(value);
        Cookies.set('order_phone', value)
    }
    function onChangeRemark(value) {
        setRemark(value);
        Cookies.set('order_remark', value)
    }
    function onChangeIDCard(value) {
        setIdcard(value);
        Cookies.set('order_idcard', value)
    }
    //  新增/修改游客信息
    function onAddFormFinish(values) {
        const { contact, idcard, telphone } = values;
        let params = {
            id: updateId,
            idCard: idcard,
            name: contact,
            phoneNum: telphone || userInfo?.phone,
            ticketType: "",
            ticketTypeDesc: "",
        }
        _addCustomer(params).then(res => {
            const { code } = res;
            if (code === 0) {
                message.success('操作成功');
                getCustomerList();
                !updateId && form.resetFields()
            }
        })
    }
    // 修改游客信息，填充form表单
    function updateCustomer(item) {
        const { id = "", name = "", idCard = "", phoneNum = "" } = item;
        form.setFieldsValue({
            contact: name,
            idcard: idCard,
            telphone: phoneNum
        });
        setUpdateId(id);
    }
    // 选择实名游客
    function selectCustomer(item) {
        if (realName === 2) {
            customerList.forEach(c => {
                c.checked = false
                if (item.id === c.id) {
                    c.checked = true
                }
            })
        } else if (realName === 3) {
            customerList.forEach(c => {
                if (item.id === c.id) {
                    c.checked = !c.checked
                }
            })
        }
        setCustomerList([...customerList]);
        setSelectCustomerToCookie(customerList);
        fillFormData(customerList);
    }
    // 删除已选择游客
    function deleteSelectCustomer(id) {
        for (let i = 0, len = customerList.length; i < len; i++) {
            const item = customerList[i];
            if (item.id === id) {
                item.checked = false;
                break
            }
        }
        setCustomerList([...customerList]);
        setSelectCustomerToCookie(customerList);
        fillFormData(customerList);
    }
    // 设置游客信息填充，选择游客时，默认填充第一条
    function fillFormData(list) {
        setContact("");
        setIdcard("");
        Cookies.remove('order_contact');
        Cookies.remove('order_phone');
        Cookies.remove('order_idcard');
        for (let i = 0; i < list.length; i++) {
            const { checked, name, idCard } = list[i];
            if (checked) {
                setContact(name);
                setIdcard(idCard);
                Cookies.set('order_contact', name);
                Cookies.set('order_phone', userInfo?.phone);
                Cookies.set('order_idcard', idCard);
                break
            }
        }
        fillFormNum(list)
    }
    // 选择游客时，根据数量重置价格
    function fillFormNum(list) {
        let num = 0;
        for (let i = 0; i < list.length; i++) {
            const { checked } = list[i]
            if (checked) {
                num += 1
            }
        }
        if (realName === 3) {
            onNumberChange(num)
        }
        if (realName === 2) {
            onNumberChange(Cookies.get('order_amount'))
        }
    }

    // Component: 新增游客信息，form表单弹出框
    const popFillForm = (
        <section className={styles['fill-form']}>
            <h3>添加/修改信息</h3>
            <Form
                form={form}
                onFinish={onAddFormFinish}
                autoComplete="off"
            >
                <Form.Item
                    label="联系人"
                    name="contact"
                    rules={[{ required: true, message: '请输入姓名' }]}
                >
                    <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                    label="身份证号"
                    name="idcard"
                    rules={[
                        { required: true, message: '请输入身份证号' },
                        {
                            validator: (rules, value, callback) => {
                                const { status, msg } = validateIDCard(value);
                                !status ? callback(msg) : callback()
                            }
                        }
                    ]}
                >
                    <Input placeholder="请输入身份证号" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        </section>
    )

    // Component: 选择游客信息
    const popSelectForm = (
        <section className={styles['fill-select']}>
            <Popover placement="rightTop" trigger="click" content={popFillForm} >
                <button className={styles['fill-btn']} onClick={() => { updateCustomer({}) }}>
                    <PlusCircleOutlined /> 添加游客
                </button>
            </Popover>
            <h3>选择游客信息</h3>
            {
                customerList.length ?
                    customerList.map((item) => {
                        return (
                            <dl key={item.id}>
                                <dd onClick={() => { selectCustomer(item) }}>
                                    <Checkbox checked={item.checked} />
                                </dd>
                                <dd>{item.name}</dd>
                                <dd>{item.idCard}</dd>
                                <dd>
                                    <Popover placement="rightTop" trigger="click" content={popFillForm} >
                                        <EditOutlined onClick={() => { updateCustomer(item) }} />
                                    </Popover>
                                </dd>
                            </dl>
                        )
                    }) : <p>暂无游客信息</p>
            }
        </section>
    )

    // Component: 需要实名信息，填写身份证
    const realNameShow = (
        realName > 1 ?
            <>
                <p className={styles['fill-tip']}>
                    <ExclamationCircleOutlined />
                    {realName === 2 ? '注：该订单需要一名游客提供实名信息' : '注：该订单需要每位游客提供实名信息'}
                </p>
                <div className={styles['fill-btns']}>
                    <Popover placement="topLeft" trigger="click" content={popSelectForm}>
                        <button className={styles['fill-btn']}><SelectOutlined /> 选择游客</button>
                    </Popover>
                </div>
                <div className={styles['fill-user']}>
                    <h3>游客信息</h3>
                    {
                        !customerList.filter(item => item.checked).length ? <p>未选择游客信息</p> : ""
                    }
                    {
                        customerList.map((item) => {
                            if (item.checked) {
                                return (
                                    <dl key={item.id}>
                                        <dd>{item.name}</dd>
                                        <dd>{item.idCard}</dd>
                                        <dd><CloseCircleOutlined onClick={() => { deleteSelectCustomer(item.id) }} /></dd>
                                    </dl>
                                )
                            }
                            return null
                        })
                    }
                </div>
            </> : ""
    )
    // Component: 填写联系人/电话 / 身份证号
    const NumberInput = (
        <div className={styles['fill-number']}>
            <span className={styles['label']}>{isHotel ? '房间数' : '数量'}</span>
            <InputNumber
                placeholder="请输入数量"
                min={minNum}
                max={maxNum}
                value={orderNum}
                onChange={(v) => { onNumberChange(v) }}
            />
        </div>
    )
    const fillContact = (
        <>
            {
                isHotel ? 
                NumberInput :
                (realName < 3 ? NumberInput : "")
            }
            <div className={styles['fill-info']}>
                <span className={styles['label']}>联系人</span>
                <Input
                    placeholder="请输入姓名"
                    value={contact}
                    onChange={(e) => onChangeContact(e.target.value)}
                />
                <span className={styles['label']}>手机号</span>
                <Input
                    placeholder="请输入手机号"
                    value={telephone}
                    onChange={(e) => onChangePhone(e.target.value)}
                />
                {   // 酒店，显示输入身份证号
                    isHotel ?
                        <>
                            <span className={styles['label']}>身份证号</span>
                            <Input
                                placeholder="请输入身份证号"
                                value={idcard}
                                onChange={(e) => onChangeIDCard(e.target.value)}
                            />
                        </> : ""
                }
            </div>
        </>
    )
    // Component: 填写备注，只有线路才有
    const fillRemark = (
        <div className={styles['fill-info']}>
            <span className={styles['label']}>备注(选填)</span>
            <TextArea
                placeholder="如有特殊情况和特殊人群请重点备注"
                value={remark}
                onChange={(e) => onChangeRemark(e.target.value)}
                autoSize={{ minRows: 3, maxRows: 5 }}
            />
            <p>提示：报名参加旅游线路时，请确保身体状况良好适合参加线路行程；如身体不适，请务必将自身健康状况如实告知。</p>
        </div>
    )
    return (
        <div className={styles['product-fill']}>
            {realNameShow}
            {fillContact}
            {
                target === '/line' ? fillRemark : ""
            }
        </div>
    )
}
const mapStateToProps = (state) => {
    return {
        order: state.order
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        _setProductInfo: (v) => dispatch(setProductInfo(v))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(OrderForm)